<template>
  <div class="app-container calendar-list-container">
    <basic-container>
      <div style="display: flex;align-content: center;align-items: center;margin-left: 20px;">
        <div v-if="isShowShop" style="display: flex;align-items: center">
          <div style="display: flex;align-content: center;align-items: center;">
            <div style="white-space: nowrap">类型名称：</div>
            <avue-crud-select
              v-model="searchType"
              size="small"
              @change="searchChange"
              placeholder="请选择类型"
              :dic="typeOptions"
              :props="typeProps"
            ></avue-crud-select>
          </div>
          <div style="white-space: nowrap;margin-left: 20px">商铺列表：</div>
          <div style="width: 240px;">
            <avue-crud-select
              @change="handlerSearchShopChange"
              size="small"
              placeholder="请选择商铺"
              :dic="shopsOptions"
              :props="shopsProps"
            ></avue-crud-select>
          </div>
        </div>
      </div>
      <div class="filter-container" style="margin-top: 30px">
        <el-button-group>
          <el-button type="primary" icon="plus" size="small" @click="handlerAdd">添加</el-button>
        </el-button-group>
      </div>

      <el-row>
        <el-col :span="12" style="margin-top:15px;">
          <el-tree
            class="filter-tree"
            node-key="id"
            highlight-current
            accordion
            default-expand-all
            :data="treeData"
            :default-expanded-keys="aExpandedKeys"
            :filter-node-method="filterNode"
            :props="defaultProps"
            :expand-on-click-node="false"
          >
            <div class="custom-tree-node" slot-scope="{ node, data }" style="display: flex">
              <div style="width: 200px;line-height: 28px">{{ node.label }}</div>
              <div>
                <el-button
                  v-if="node.data.parentId==-1"
                  type="text"
                  size="mini"
                  @click="getNodeData(node.data.id)"
                >增加
                </el-button>
                <el-button type="text" size="mini" @click="handlerGetEditData(node.data.id)">编辑</el-button>
                <el-button type="text" size="mini" @click="handleDelete(node.data.id)">删除</el-button>
              </div>
            </div>
          </el-tree>
        </el-col>
        <el-col :span="12" style="margin-top:15px;">
          <el-card class="box-card">
            <el-form
              :label-position="labelPosition"
              label-width="80px"
              :model="form"
              :rules="rules"
              ref="form"
            >
              <el-form-item label="标题" prop="name">
                <el-input v-model="form.name" :disabled="formEdit" placeholder="请输入标题"></el-input>
              </el-form-item>
              <el-form-item label="服务类型" prop="merSerTypeId">
                <avue-crud-select
                  v-model="form.merSerTypeId"
                  size="small"
                  @change="searchChange"
                  :disabled="shopEdit"
                  placeholder="请选择服务类型"
                  :dic="typeOptions"
                  :props="typeProps"
                ></avue-crud-select>
              </el-form-item>
              <el-form-item label="商铺" prop="shopId">
                <avue-crud-select
                  v-model="form.shopId"
                  @change="handlerSearchShopChange"
                  placeholder="请选择商铺"
                  :dic="shopsOptions"
                  :props="shopsProps"
                  :disabled="shopEdit"
                ></avue-crud-select>
              </el-form-item>
              <el-form-item label="是否推荐" prop="isRecommend">
                <el-radio-group v-model="form.isRecommend">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="排序" prop="sort">
                <el-input
                  type="number"
                  v-model="form.sort"
                  :disabled="formEdit"
                  placeholder="请输入排序"
                ></el-input>
              </el-form-item>
              <el-form-item v-if="formStatus == 'update'">
                <el-button type="primary" @click="update">更新</el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
              <el-form-item v-if="formStatus == 'create'">
                <el-button type="primary" @click="create">保存</el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>

<script>
  import {
    getObj,
    addObj,
    putObj,
    delObj,
    fetchCateTree
  } from '@/api/merchantservices/category'
  import {getListByType} from '@/api/merchantservices/merservicestype'
  import {mapGetters} from 'vuex'
  import {getShopsByType} from '@/api/shop/shops'

  export default {
    name: 'category',
    data () {
      return {
        shopsProps: {
          label: 'shopName',
          value: 'id'
        },
        typeProps: {
          label: 'name',
          value: 'id'
        },
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        labelPosition: 'right',
        aExpandedKeys: [],
        form: {
          name: '',
          isRecommend: 0,
          id: null,
          parentId: null,
          sort: 100,
          shopId: null,
          merSerTypeId: null
        },
        formEdit: true,
        shopEdit: true,
        formAdd: true,
        formStatus: '',
        searchShopId: '',
        isShowShop: false,
        searchType: '',
        loading: false,
        shopsOptions: [],
        typeOptions: [],
        currentParentId: -1,
        rules: {
          name: [{required: true, message: '请输入分类名称', trigger: 'blur'}],
          parentId: [
            {required: true, message: '请输入上级id', trigger: 'blur'}
          ],
          sort: [{required: true, message: '请输入排序', trigger: 'blur'}],
          shopId: [{required: true, message: '请选择商铺', trigger: 'blur'}],
          merSerTypeId: [
            {required: true, message: '请选择服务类型', trigger: 'blur'}
          ]
        }
      }
    },
    mounted: function () {
      this.getSeversType()
      // this.getBrandTypeList()
      this.searchShopId = this.$store.state.user.shopId
      if (this.searchShopId) {
        this.isShowShop = false
      } else {
        this.isShowShop = true
      }
    },
    computed: {
      ...mapGetters(['elements'])
    },
    methods: {
      // 获取服务类型
      getSeversType () {
        const data = new FormData()
        data.append('types', [3, 5])
        getListByType(data).then(res => {
          console.log(res)
          this.typeOptions = res.data.data
        })
      },
      // 根据选择的服务类型获取门店
      searchChange (e) {
        if (e) {
          this.form.merSerTypeId = e
          for (let i = 0; i < this.typeOptions.length; i++) {
            if (this.typeOptions[i].id == e) {
              const data = new FormData()
              data.append('shopId', this.$store.state.user.shopId)
              data.append('type', this.typeOptions[i].type)
              getShopsByType(data).then(res => {
                this.shopsOptions = res.data.data
                this.searchShopId = this.shopsOptions[0].id
                if (this.searchShopId) {
                  this.form.shopId = this.shopsOptions[0].id
                }
              })
            }
          }
        }
      },

      // 根据选择的门店获取类目数据
      handlerSearchShopChange (e) {
        if (e) {
          this.searchShopId = e
          // const data = new FormData();
          // data.append("merSerTypeId",  ? this.form.merSerTypeId : 'null');
          // data.append("shopId", e ? e : '');
          fetchCateTree({'merSerTypeId': this.form.merSerTypeId || null, 'shopId': e || null}).then(response => {
            // if (response)
            console.log(response)
            this.treeData = response.data.data
            this.loading = false
          })
        }
      },

      filterNode (value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      getNodeData (id) {
        this.formStatus = 'create'
        this.formEdit = false
        this.shopEdit = true
        getObj(id).then(response => {
          this.resetForm()
          delete this.form.id
          this.form.parentId = id
          this.form.shopId = response.data.data.shopId
          this.form.merSerTypeId = response.data.data.merSerTypeId
        })
      },

      // 新增
      handlerAdd () {
        this.resetForm()
        this.formEdit = false
        this.formAdd = false
        this.shopEdit = false
        this.formStatus = 'create'
        delete this.form.id
        this.currentParentId = -1
        this.form.parentId = this.currentParentId
        // if (this.searchShopId) {
        //   this.form.shopId = this.searchShopId;
        // }
      },

      create () {
        addObj(this.form).then(res => {
          this.handlerSearchShopChange(this.form.shopId)
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
        })
      },

      // 修改
      handlerGetEditData (id) {
        this.formStatus = 'update'
        this.formEdit = false
        this.shopEdit = true
        getObj(id).then(response => {
          this.form = response.data.data
          this.handlerSearchShopChange(this.form.shopId)
        })
      },

      update () {
        putObj(this.form).then(() => {
          this.handlerSearchShopChange(this.form.shopId)
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      },

      // 删除
      handleDelete (id) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(id).then(res => {
            if (res.data.code === 0) {
              this.handlerSearchShopChange(this.form.shopId)
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: res.data.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        })
      },
      onCancel () {
        this.formEdit = true
        this.formStatus = ''
      },
      resetForm () {
        this.form.name = ''
        this.form.id = ''
        this.form.parentId = ''
        this.form.sort = ''
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
